package com.ak.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * header携带token验证过滤器
 *
 * @author xk
 * @create 2023/12/6 14:23
 * @since 1.0.0
 */
public class HeaderTokenGateWayFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //从HttpHeader中寻找key为token，value为butool的键值对
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if("akToken".equals(token)){
            return chain.filter(exchange);
        }
        // 标记此次请求没有权限，并且结束这次请求
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //请求结束
        return exchange.getResponse().setComplete();
    }

    /**
     * 优先级
     * @return
     */
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE+2;
    }

}
